<?php

class PHPFaces{

	public static $dom;
	
	public static function loadPHPFacesScripts(){
		static $carregou = false;
		if (!$carregou){
			PHPFaces::addScript(null, 'var URL="'.URL.'";');
			PHPFaces::addScript(URL.'phpFaces/jquery.js');
			PHPFaces::addScript(URL.'phpFaces/phpfaces.js');
			$carregou = true;
		}
	}
	
	public static function addScript($arquivo, $inline = ''){
		$dom = PHPFaces::$dom;

		if (!empty($arquivo)){
			$scripts = $dom->getElementsByTagName('script');
			foreach($scripts as $script){
				if($script->getAttribute('src') == $arquivo)
					return true; 
			}
		}
		
		$head = $dom->getElementsByTagName('head');
		if ($head->length == 0)
			return false;
			
		$script = $dom->createElement('script');
		$script->setAttribute('type', 'text/javascript');
		if (!empty($arquivo))
			$script->setAttribute('src', $arquivo);
		else
			$script->nodeValue = $inline;
		$head->item(0)->appendChild($script);
		return true;		
	}
	
	public static function json($data){           
	    if(is_array($data) || is_object($data)){
	        $islist = is_array($data) && ( empty($data) || array_keys($data) === range(0,count($data)-1) );
	        if( $islist ){
	            $json = '[' . implode(',', array_map('PHPFaces::json', $data) ) . ']';
	        }else{
	            $items = array();
	            foreach( $data as $key => $value )
	                $items[] = PHPFaces::json("$key").':'.PHPFaces::json($value);
	            $json = '{'.implode(',', $items).'}';
	        }
	        return $json;
	    }elseif(is_string($data)){
	    	return '"'.str_replace(array("\r","\n","\t","\f"), array('','\n','\t','\f'), addcslashes($data,'"\\')).'"';
	    }
        # int, floats, bools, null
        return strtolower(var_export($data, true));
	}	
	
}

?>